﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Windows.Forms;

namespace StudentApartMentManage
{
    public partial class StayOut : Form
    {
        public StayOut()
        {
            InitializeComponent();
        }
        string GetRstr(string sql, int i)
        {
            string[] str = new string[2];
            string connectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            SqlDataReader r = cmd.ExecuteReader();
            if (r.Read())
            {
                str[i] = r.GetString(i);
            }
            r.Close();
            con.Close();
            return str[i];
        }
        private void StayOut_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = DataShow.show("select * from 公寓分配表");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string sql = string.Format("select * from 公寓分配表 where 学号='{0}'", textBox1.Text.Trim());
                dataGridView1.DataSource = sqlHelper.GetTable(sql);
                MessageBox.Show("查找成功!");
            }
            catch(Exception ex)
            {
                MessageBox.Show("查找失败!");
                return;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string sql0 = string.Format("select 姓名 from 公寓分配表 join 学生信息表 on 公寓分配表.学号=学生信息表.学号 where 公寓分配表.学号='{0}'", dataGridView1.SelectedCells[3].Value.ToString().Trim());
                string sname = GetRstr(sql0, 0);
                if (MessageBox.Show("学生"+sname+"真的要退宿吗?","警告",MessageBoxButtons.YesNo)==DialogResult.Yes)
                {
                    string sql = string.Format("delete from 公寓分配表 where 学号='{0}'", dataGridView1.SelectedCells[3].Value.ToString());
                    int i = sqlHelper.Execute(sql);
                    if(i!=-1)
                    {
                        MessageBox.Show("退宿成功");
                        dataGridView1.DataSource = DataShow.show("select * from 公寓分配表");
                    }else
                    {
                        MessageBox.Show("退宿失败!");
                        return;
                    }
                }

            }
            catch(Exception ex)
            {
                MessageBox.Show("退宿失败!");
                return;
            }
            
        }
    }
}
